package com.example._01helloword.controller;

import com.example._01helloword.model.Person;
import com.example._01helloword.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

@RestController
public class UserController {
    @RequestMapping(value = "/getUser",method = RequestMethod.GET)
    public User getUser(){
        User user=new User();
        user.setName("张三");
        user.setAge(18);
        user.setPass("111111");
        return user;
    }

    @RequestMapping(value = "/getUser2",method = RequestMethod.GET)
    public User getUser2(String username){
        User user=new User();
        user.setName(username);
        user.setAge(18);
        user.setPass("111111");
        return user;
    }

    @RequestMapping(value = "/getUser3",method = RequestMethod.GET)
    public User getUser3(User user){
        return user;
    }

    @RequestMapping(value = "/getUser4/{name}",method = RequestMethod.GET)
    public User getUser4(@PathVariable String name){
        User user=new User();
        user.setName(name);
        user.setAge(18);
        user.setPass("111111");
        return user;
    }

    @RequestMapping(value = "/saveUser",method = RequestMethod.POST)
    public String saveUser(@Valid User user, BindingResult result){
        System.out.println(user);
        if(result.hasErrors()){
            List<ObjectError> list=result.getAllErrors();
            for(ObjectError e:list){
                System.out.println(e.getCode()+"--"+e.getDefaultMessage());
            }
        }
        return "ok";
    }

    @Autowired
    private Person person;
    @RequestMapping("/testPerson")
    public Person testPerson(){
        return person;
    }
}
